package tpi.gui.pages.pais

import dominio.ubicaciones.Pais
import org.apache.wicket.markup.html.WebPage
import org.apache.wicket.markup.html.basic.Label
import org.apache.wicket.markup.html.form.Form
import org.apache.wicket.markup.html.form.TextField
import org.apache.wicket.markup.html.panel.FeedbackPanel
import org.apache.wicket.model.CompoundPropertyModel
import org.uqbar.commons.model.UserException
import org.uqbar.wicket.xtend.WicketExtensionFactoryMethods
import org.uqbar.wicket.xtend.XButton
import tpi.gui.panels.info.CaracteristicasPanel
import tpi.gui.panels.info.ConexionesPanel
import tpi.gui.panels.info.LugaresPanel
import tpi.gui.pages.mapamundi.MapamundiPage

class PaisPage extends WebPage {
	
	extension WicketExtensionFactoryMethods = new WicketExtensionFactoryMethods
	private final Pais original
	private final Pais copia
	private final MapamundiPage mainPage
	
	new(Pais original,Pais copia, MapamundiPage mainPage) {
		this.defaultModel = copia.asCompoundModel
		this.original = original
		this.copia = copia
		this.mainPage = mainPage
		
		addChild(new Label("titulo", if(editando) "Edicion de Pais" else "Nuevo Pais"))
		val Form<Pais> form = new Form<Pais>("paisForm", new CompoundPropertyModel(this.copia))
		form.addChild(new TextField<String>("nombre"))
		form.agregarCaracteristicasPanel
		form.agregarConexionesPanel
		form.agregarLugaresPanel
		form.addChild(new FeedbackPanel("feedbackPanel"))
		form.addChild(new XButton("aceptar").onClick = [| aceptar()])
		form.addChild(new XButton("volver").onClick = [| volver()])

		addChild(form)
	}
	
	def agregarCaracteristicasPanel(Form<Pais> mainForm) {
		mainForm.addChild(new CaracteristicasPanel("caracteristicas", this.copia))
	}

	def agregarConexionesPanel(Form<Pais> mainForm) {
		mainForm.addChild(new ConexionesPanel("conexiones", this.copia))
	}

	def agregarLugaresPanel(Form<Pais> mainForm) {
		mainForm.addChild(new LugaresPanel("lugares", this.copia))
	}
	
	def aceptar() {
		try {
			copia.validar()
			if(editando) {
				val index = original.mapamundi.paises.indexOf(original)
				original.mapamundi.paises.set(index, copia)
			} else {
				copia.mapamundi.agregarPais(copia)
			}
			responsePage = mainPage
		} catch (UserException e) {
			info(e.getMessage())
		} 
	}
	
	def editando() {
		original != null
	}
	
	def volver() {
		responsePage = this.mainPage
	}
	
}